import React, { useEffect, useState } from 'react';
import SearchOutlined from '@material-ui/icons/SearchOutlined';
import { obj_bool, for_obj, obj_empty, obj_str, NavListSub } from 'sui';
import { TraceView } from './trace';
import { urlWork } from 'nui';

const Trace = ({ mod }) => <TraceView mod={mod}/>;

const reload = (setMain) => {
    const hcustom = (ret, hcmd) => {
        urlWork(null, "cache/get", {uid: "custom"},
            r => {
                for_obj(r, (k, v) => {
                    const id = obj_str(v, "id");
                    ret[k] = id;
                });
                hcmd();
            }, e => hcmd());
    };

    const hit = (ret, hcmd) => {
        urlWork(null, "cache/list", {mod: "it"},
            r => {
                r.forEach(d => {
                    const db_save = obj_bool(d, "db_save");
                    if (!db_save) {
                        return;
                    }

                    const uid = obj_str(d, "uid");
                    const name = obj_str(d, "name");

                    ret[uid] = name;
                });

                hcmd();
            }, e => hcmd());
    };

    const ret = {};

    hcustom(ret, () => hit(ret, () => setMain(ret)));
};

const NavTrace = ({ event, setEvent, ...props }) => {
    const [main, setMain] = useState();

    useEffect(() => reload(setMain), []);

    useEffect(() => {
        if (event) {
            const v = event.split(",");
            const f = v.find(d => "update");
            if (f) {
                reload(setMain);
                setEvent("");
            }
        }
    }, [event, setEvent]);

    const get_model = () => {
        if (obj_empty(main)) {
            return null;
        }

        let ret = [];

        for_obj(main, (k, v) => {
            ret.push({uid: `trace.${k}`, value: v, sub: k});
        });

        ret.sort((a, b) => a.value > b.value);

        return ret;
    };

    return <NavListSub icon={<SearchOutlined/>} sub={get_model()} {...props} scut={15}/>;
};

export {NavTrace, Trace};
